<template>
  <div class="app-container">
      <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>经销商数据列表</span>
      <!-- <el-button class="btn-add" @click="handleAddProduct()" size="mini">
        添加新经销商
      </el-button> -->
    </el-card>
    <el-table ref="productTable"
          :data="list"
          style="width: 100%;margin-bottom: 20px;"
          v-loading="listLoading"
          row-key="id"
          border
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope"> {{scope.row.id}} </template>
        </el-table-column>
        <el-table-column label="用户名" width="200" align="center">
          <template slot-scope="scope"> {{scope.row.nickname}} </template>
        </el-table-column>
        <el-table-column label="邀请码" width="200" align="center">
          <template slot-scope="scope">{{scope.row.invitationCode}}</template>
        </el-table-column>
        <el-table-column label="提现账号" width="200" align="center">
          <template slot-scope="scope">{{scope.row.withdrawAccount}}</template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">{{scope.row.status==0?'未启用':'启用'}}</template>
        </el-table-column>
        <el-table-column label="优惠信息" width="200" align="center">
          <template slot-scope="scope">
          {{scope.row.promotionContent }}
          </template>
        </el-table-column>
        <el-table-column label="分润比例" align="center">
          <template slot-scope="scope">{{scope.row.profitPercent}}</template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleEditSalesman(scope.$index, scope.row)">编辑
              </el-button>
              <!-- <el-button
                size="mini"
                @click="handleUpdateSalesman(scope.$index, scope.row)">分配经销商
              </el-button> -->
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteSalesman(scope.$index, scope.row)">删除
              </el-button>
          </template>
        </el-table-column>
    </el-table>
    <!-- 新增经销商的弹窗 -->
    <!-- <el-dialog title="新增经销商" :visible.sync="isNewSalesmanOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="newForm" style="width:25rem;" :rules="newFormRules" >
            <el-form-item label="用户名" prop="nickname" required label-width="5rem">
                <el-input v-model="newForm.nickname" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="优惠信息"  prop="sort" label-width="5rem">
                <el-input v-model="newForm.desc" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
             <el-form-item label="分润比例"  prop="sort" label-width="5rem">
                <el-input  v-model="newForm.tatio" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveNewSalesman('newForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isNewSalesmanOpen = false">关闭</el-button>
        </div>
    </el-dialog> -->
    <!-- 编辑经销商的弹窗 -->
    <el-dialog title="编辑经销商" :visible.sync="isEditSalesmanOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="editForm" style="width:25rem;" :rules="editFormRules" >
            <el-form-item label="用户名" prop="nickname" required label-width="5rem">
                <el-input :disabled="true" v-model="editForm.nickname" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="邀请码" prop="invitationCode" required label-width="5rem">
                <el-input :disabled="true" v-model="editForm.invitationCode" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
            <el-form-item label="启用经销商">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="editForm.status">
              </el-switch>
            </el-form-item>
            <el-form-item label="分润比例"  prop="sort" label-width="5rem">
                <el-input  v-model="editForm.tatio" style="width:16.66rem;" placeholder="除以100以后去计算真实分润金额"></el-input>
            </el-form-item>
            <el-form-item label="优惠信息" label-width="5rem">
             <el-select v-model="editForm.discountId" placeholder="请选择" @change="handleSelectionChange" >
              <el-option v-for="item in promotionList.list" v-bind:key="item.index" :value="item.id" :label="item.label">
                <!-- <p v-if="item.type ==1">满{{item.exchangeFullPrice}}减{{item.exchangeReducePrice}}</p>
                <p v-else-if="item.type ==2">{{item.discount}}折</p>
                <p v-else>满{{item.exchangeFreeFreight}}免邮</p> -->
              </el-option>
            </el-select>
            <el-button type="primary" size="small" @click="deletePromotion">删除优惠</el-button>
            </el-form-item>
            <el-form-item label="描述"  prop="sort" label-width="5rem">
                <el-input  v-model="editForm.desc" placeholder="" style="width:16.66rem;"></el-input>
            </el-form-item>
        </el-form>
      <div style="clear: both;"></div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveSalesmanInfo('editForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isEditSalesmanOpen = false">关闭</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
    import {
    fetchSalesmanList,
    updateSalesmanInfo,
    newSalesmanInfo,
    deleteSalesman,
    fetchSalesDiscountList,
    setSalesmanRadio,
    deleteSalemanPromotion
  } from '@/api/salesman'


  const defaultListQuery = {
    nickname: null,
    pageNum: 1,
    pageSize: 5,
  };
  export default {
    name: "SalesmanList",
    data() {
      return {
          list:[],
          defaultProps: {
            children: 'children',
            label: 'label'
            },
          listQuery:Object.assign({}, defaultListQuery),
          newForm:{//新增经销商弹框里内容
            nickname:'',
            invitationCode:'',
            desc:'',
            status:1,
            tatio:0,
          },
          editForm: {//编辑经销商弹框里内容
            nickname:'',
            invitationCode:'',
            desc:'',
            discountId:null,//优惠id
            //multipleSelection:[],
            status:1,
            tatio:0,
          },
          promotionList:{
            list:[],
            listQuery:{
              keyword: null,
              pageNum: 1,
              pageSize: 5,
            },
            total:null,
          },
          newFormRules:{
            nickname:[
                { required: true,  message: '经销商名不能为空', trigger: ['blur','change']}
             ],
            invitationCode:[
                { required: true,  message: '链接不能为空', trigger: ['blur','change']}
             ],
          },
          editFormRules:{
            nickname:[
                { required: true,  message: '经销商名不能为空', trigger: ['blur','change']}
             ],
             invitationCode:[
                { required: true,  message: '链接不能为空', trigger: ['blur','change']}
             ],
          },

          isNewSalesmanOpen:false,//新增经销商弹窗
          isEditSalesmanOpen:false,//编辑经销商弹窗
         
      }
    },
    created() {
      this.getList();
    },
    methods:{
      //删除经销商的优惠
      deletePromotion(){
        let self = this;
        let id = self.editForm.currentUId;
        console.log(id);
        if(id){
          deleteSalemanPromotion(id).then(res=>{
            if(res.code ==200){
              self.editForm.discountId =null
            }
          })
        }
        
      },
      getList() {
        this.listLoading = true;
        fetchSalesmanList().then(response => {
            if(response.code === 200){
               this.listLoading = false;
                let res = response.data;
                //this.list = res.list;
                this.total = response.data.total;
                this.totalPage = response.data.totalPage;
                this.pageSize = response.data.pageSize;
               // this.getPromotionList();
                fetchSalesDiscountList().then(resp=>{
                  let tempList = resp.data.list;
                  this.promotionList.total = resp.data.list.total;
                  tempList.map((item)=>{
                    if(item.type==1){
                      item.label = '满'+item.fullPrice+'减'+item.reducePrice
                    }else if(item.type ==2){
                      item.label = item.discount+'折'
                    }else{
                      item.label ='满'+item.freeFreight+'免邮'
                    }
                  })
                  //tempList.unshift({id:null,type:null,label:'无优惠',discountId:null})
                  this.promotionList.list = tempList;
                  res.list.forEach((item,index)=>{
                    let discountId = item.discountId;
                    let targetIdx =null;
                   let length = resp.data.list.length;
                   for(let i = 0;i <length; i++){
                    if(resp.data.list[i].id==discountId){
                      targetIdx = i;
                    }
                   }
                   if(typeof(targetIdx) == 'number'){
                     let currentPromotion= resp.data.list[targetIdx];
                     let desc ='';
                     if(currentPromotion.type ==1){
                      desc = '满' +currentPromotion.fullPrice +'减' + currentPromotion.reducePrice
                     }else if( currentPromotion.type ==2){
                       desc =currentPromotion.discount +'折'
                     }else{
                       desc= '满'+currentPromotion.freeFreight+'免邮'
                     }
                      item.promotionContent = desc;
                   }
                  })
                  this.list = res.list;
                })
            }
        });
      },
      setRadio(uid,radio){
        if(!radio){//如果没有传值，就不去保存
          return
        }
        setSalesmanRadio(uid,radio).then(res=>{
          if(res.code ==200){
            this.getList();
          }
        })
      },
      searchQueryList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleEditSalesman(index,item){
        let self = this;
        self.isEditSalesmanOpen = true;
        self.editForm = Object.assign(self.editForm,JSON.parse(JSON.stringify(item)));
        self.editForm.currentUId = item.id;
        self.editForm.tatio = item.profitPercent;
        if(item.discountId){
          self.editForm.discountId = item.discountId;
        }
      },
      getPromotionList(){
        fetchSalesDiscountList().then(res=>{
          let tempList = res.data.list;
          this.promotionList.total = res.data.list.total;
          tempList.map((item)=>{
            if(item.type==1){
              item.label = '满'+item.fullPrice+'减'+item.reducePrice
            }else if(item.type ==2){
              item.label = item.discount+'折'
            }else{
              item.label ='满'+item.freeFreight+'免邮'
            }
          })
          this.promotionList.list = tempList;
          console.log(this.promotionList.list)
        })
      },
      handleSelectionChange(val){
        console.log(val);
        this.editForm.discountId = val;
        this.$forceUpdate();
      },
      handleAddProduct(){
          this.isNewSalesmanOpen = true;
      },
      // saveNewSalesman(){
      //     let self= this;
      //     self.newForm.description = self.newForm.name;
      //     console.log(self.newForm);
      //   newSalesmanInfo(self.newForm).then(response=>{
      //       if(response.code == 200){
      //           self.$message({
      //           message: '新建成功',
      //           type: 'success',
      //           duration: 1000
      //       });
      //       this.setRadio(response.data,self.newForm.tatio);
      //       self.isNewSalesmanOpen=false;
      //       self.getList();
      //     }
      //   })
      // },
      saveSalesmanInfo(){
          console.log(this.editForm);
        // this.editForm.discountId = this.editForm.multipleSelection.id;
        updateSalesmanInfo(this.editForm.currentUId,this.editForm).then(response=>{
            this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1000
            });
            if(this.editForm.tatio){
              this.setRadio(this.editForm.currentUId,this.editForm.tatio);
              this.editForm.tatio =0;
              this.isEditSalesmanOpen=false;
            }else{
              this.editForm.tatio =0;
              this.isEditSalesmanOpen=false;
              this.getList();
            }
            
            
        });
      },
       handleDialogSizeChange(val) {
        this.editForm.listQuery.pageNum = 1;
        this.editForm.listQuery.pageSize = val;
        this.getPromotionList();
      },
      handleDialogCurrentChange(val) {
        this.editForm.listQuery.pageNum = val;
        this.getPromotionList();
      },
      handleDeleteSalesman(index,item){
          let self = this;
           self.$confirm('删除该经销商, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                // let arrTemp= [];
                // arrTemp.push(item.id);
                // //objTemp.ids = arrTemp;
                // let params = new URLSearchParams();
                // params.append('id', arrTemp);
                let delId=item.id;
                deleteSalesman(delId).then(response=>{
                    if(response.code === 200){
                        self.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1000
                        });
                        self.getList();
                    }
                });
            }).catch(() => {
                // self.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });          
            });
      },
      
    }
  }
</script>
<style scoped>
.btn-add{
    font-size: 14px;
    padding: 10px;
    margin-top: -8px;
  color:#fff;
  background-color:#417FF6;
}
/* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 

.editform-promotion >>> tr.current-row td{
  background-color: #999;
}
</style>